package com.puhui.lib.http.retrofit;

import android.app.Activity;

import com.blankj.utilcode.util.ActivityUtils;
import com.puhui.lib.http.CookieUtils;
import com.puhui.lib.http.retrofit.converter.StringConverterFactory;
import com.puhui.lib.utils.PHConstant;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

public class HttpManager {
    private static final int DEFAULT_TIMEOUT = 30;

    private static volatile HttpManager httpManager = null;
    private static Retrofit apiRetrofit;
    private OkHttpClient okHttpClient;

    private HttpManager() {
        initRetrofit();
    }

    public static HttpManager getInstance() {
        if (httpManager == null) {
            synchronized (HttpManager.class) {
                if (httpManager == null) {
                    httpManager = new HttpManager();
                }
            }
        }
        return httpManager;
    }

    private OkHttpClient getOkHttpClient() {
        if (null == okHttpClient) {
            okHttpClient = new OkHttpClient().newBuilder()
                    .addInterceptor(mHeaderInterceptor)
                    .addInterceptor(new SaveCookiesInterceptor())
                    .addInterceptor(new BaseParamsInterceptor())
                    .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
//                    .cookieJar(new CookieManger(AppManager.getAppManager().currentActivity()))
                    .build();

        }
        return okHttpClient;
    }

    private void initRetrofit() {
        apiRetrofit = new Retrofit.Builder()
                .baseUrl(PHConstant.BASE_API_URL)
                .client(getOkHttpClient())
//                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(StringConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    BaseServiceApi createApiService() {
        return apiRetrofit.create(BaseServiceApi.class);
    }

    <T> void toSubscribe(Observable<T> o, Observer<T> s) {
        o.subscribeOn(Schedulers.io())//事件在IO线程执行
                .unsubscribeOn(Schedulers.io())//解绑在IO线程
                .observeOn(AndroidSchedulers.mainThread())//回调在主线程
                .subscribe(s);
    }

    private Interceptor mHeaderInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Activity activity = ActivityUtils.getTopActivity();
            if (null != activity) {
                String accessToken = CookieUtils.getCookie(activity);
                request = request.newBuilder()
//                        .addHeader("Content-Type", "application/json;charset=UTF-8")
////                        .addHeader("Content-Type", "multipart/form-data")
//                        .addHeader("Accept-Encoding", "gzip, deflate")
//                        .addHeader("Connection", "keep-alive")
//                        .addHeader("Accept", "*/*")
                        .addHeader("Cookie", accessToken).build();
            }

            return chain.proceed(request);
        }
    };

    public class SaveCookiesInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            //set-cookie可能为多个
            if (!response.headers("set-cookie").isEmpty()) {
                List<String> cookies = response.headers("set-cookie");
                Activity activity = ActivityUtils.getTopActivity();
                if (null != activity) {
                    CookieUtils.setCookie(cookies);
                }
            }
            return response;
        }
    }

    class BaseParamsInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Activity activity = ActivityUtils.getTopActivity();
            if (null != activity) {
                //配置公共参数
                request = new ParamsContext(request, activity).getInRequest();
            }
            return chain.proceed(request);
        }
    }

    static <T> Observer getSubscriber(final RequestResponse<T> requestResponse) {
        return new Observer<T>() {
            @Override
            public void onError(Throwable e) {
                if (null != requestResponse) {
                    requestResponse.onFailure(e);
                }
            }

            @Override
            public void onComplete() {

            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(T result) {
                if (null != requestResponse) {
                    requestResponse.onRequestResult("", result);
                }
            }
        };
    }
}